# == Schema Information
# Schema version: 6
#
# Table name: documents
#
#  id                :integer(11)   not null, primary key
#  title             :string(255)   
#  description       :string(255)   
#  body              :text          
#  user_id           :integer(11)   
#  created_at        :datetime      default(Sat Apr 21 23:11:54 -0500 2007)
#  document_state_id :integer(11)   default(1)
#

class Document < ActiveRecord::Base
  belongs_to :user
  belongs_to :document_state
  acts_as_commentable
  acts_as_voteable
  validates_presence_of :title, :body, :user_id
  validates_numericality_of :user_id
  validates_uniqueness_of :title
  validates_associated :user, :allow_nil => false

  def validate
    unless self.user(true)
      self.errors.add(:user_id, "is not a valid user id")
    end
  end
  
  def self.find_active_documents( *users )
    @documents=Document.find_all_by_document_state_name("Comment","Vote","Approved", "Rejected")
    users.each do |user|
      @documents<<Document.find_all_by_user_id( user )
    end
    @documents.flatten!
    @documents.uniq
  end
  
  def self.find_all_by_document_state_name(*names)
    @docs=[]
    names.each do |name|
      @docs<<Document.find_all_by_document_state(DocumentState.find_by_name(name))
    end
    @docs.flatten
  end
  
  def self.find_all_by_document_state(state)
    Document.find_all_by_document_state_id(state.id).flatten
  end
  
  def next_state
    if self.document_state_id > 2 
      1
    else
      return self.document_state_id+1
    end

  end
  
  def promote
    self.document_state_id=self.next_state
    self.save!
  end
  
  def demote
    self.document_state_id = self.document_state_id - 1
    self.save
  end
  
  def approve
    self.document_state_id=DocumentState.find_by_name("Approved").id
    self.save!
  end
  
  def reject
    self.document_state_id=DocumentState.find_by_name("Rejected").id
    self.save!
  end
end
